// 平台管理器
import 'package:flutter/foundation.dart';
import 'package:flutter_again/models/video_info.dart';
import 'package:flutter_again/models/video_platform.dart';
import 'package:flutter_again/models/video_search_params.dart';
import 'package:flutter_again/models/video_search_result.dart';
import 'package:flutter_again/parsers/interfaces/video_platform_parser.dart';

class VideoPlatformManager with ChangeNotifier {
  final Map<String, VideoPlatformParser> _parsers = {};
  final Map<String, VideoPlatform> _platforms = {};

  // 注册平台解析器
  void registerParser(VideoPlatformParser parser) {
    _parsers[parser.platformId] = parser;
    _platforms[parser.platformId] = parser.platformInfo;
    notifyListeners();
  }

  void removeParser(String platformId) {
    final hasParser = _platforms.containsKey(platformId);
    if (hasParser) {
      _platforms.remove(platformId);
      notifyListeners();
    }
  }

  // 获取所有平台信息
  List<VideoPlatform> getAllPlatforms() {
    return _platforms.values.toList();
  }

  // 获取特定平台解析器
  VideoPlatformParser? getParser(String platformId) {
    return _parsers[platformId];
  }

  // 获取平台信息
  VideoPlatform? getPlatformInfo(String platformId) {
    return _platforms[platformId];
  }

  Future<String?> getVideoUrl(String platformId, String pageUrl) async {
    final parser = getParser(platformId);
    if (parser != null) {
      return await parser.getVideoUrl(pageUrl);
    }
    return null;
  }

  Future<VideoSearchResult> singleSearch( String platformId, VideoSearchParams params) {
    final parser = getParser(platformId);
    if (parser == null) {
      throw Exception('不支持的视频平台: $platformId');
    }

    return parser.search(params);
  }

  // 搜索多个平台
  Future<VideoSearchResult> search(VideoSearchParams params, {  String? platformId }) async {
    List<String> platformIds;
    if (platformId != null) {
      platformIds = [platformId];
    } else {
      platformIds = _parsers.keys.toList();
    }
    // 使用Future.await并行搜索所有平台
    final VideoSearchResult result = VideoSearchResult(
      platform: platformIds.length == 1 ? platformIds.first : 'all',
      videos: [],
      currentPage: params.page,
      hasNextPage: false
    );
    final futures = platformIds.map((id) async {
      try {
        final data = await singleSearch(id, params);
        result.videos.addAll(data.videos);
        if (platformIds.length == 1) {
          result.hasNextPage = data.hasNextPage;
          result.currentPage = data.currentPage;
        } else if (data.hasNextPage) {
          result.hasNextPage = true;
        }
      } catch(err) {/** empty */}
    });
    await Future.wait(futures);

    return result;
  }

  Future<VideoInfo?> getVideoDetail(String platformId, String videoId) async {
    final parser = getParser(platformId);
    return parser?.getVideoDetail(videoId);
  }
}